package com.ruoyi.framework.websocket;


import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能说明: TODO服务<br>
 * 开发人员: @author Mr.Wen<br>
 * 开发时间: 2024-03-09 21:39<br>
 **/
@Component
@ServerEndpoint("/ws/appCrm/{mobile}")
public class AppWebSocket {
    private static Logger logger = LogManager.getLogger(AppWebSocket.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, AppWebSocket> webSocketSet = new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //当前发消息的人员手机号
    private String mobile = "";

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        try {
            AppWebSocket.onlineCount++;
        } catch (Exception e) {
            logger.error("appWebSocket：在线人数统计（上线）异常", e.getMessage());
        }
    }

    public static synchronized void subOnlineCount() {
        try {
            if (AppWebSocket.onlineCount >= 1) {
                AppWebSocket.onlineCount--;
            }
        } catch (Exception e) {
            logger.error("appWebSocket：在线人数统计（离线）异常", e.getMessage());
        }
    }

    /**
     * websocket 连接打开
     *
     * @param param
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam(value = "mobile") String param, Session session) {
        try {
            this.session = session;
            mobile = param;
            this.session = session;
            if (StringUtils.isNotBlank(param) && webSocketSet.get(param) == null) {
                webSocketSet.put(param, this);
                addOnlineCount();
                logger.info(String.format("appWebSocket：新连接加入mobile=%s！当前在线人数为%s", mobile, getOnlineCount()));
            }
        } catch (Exception e) {
            logger.error("appWebSocket：连接打开异常", e.getMessage());
        }
    }

    /**
     * websocket 连接关闭
     */
    @OnClose
    public void onClose() {
        try {
            if (StringUtils.isNotBlank(mobile)) {
                webSocketSet.remove(mobile);
                subOnlineCount();
                logger.info(String.format("appWebSocket：用户%s连接关闭！当前在线人数为%s", mobile, getOnlineCount()));
            }
        } catch (Exception e) {
            logger.error("appWebSocket：连接关闭异常", e.getMessage());
        }
    }
    @OnError
    public void onError(Session session, Throwable throwable) {
        logger.info("appWebSocket：onError:" + throwable.getMessage());
    }

    public void sendMessage(String message, Session session) throws IOException {
        synchronized (session) {
            session.getBasicRemote().sendText(message);
        }
    }

    public boolean  sendCallPhoneMessage(String message,String phone){
        try {
        if (webSocketSet.get(phone) != null) {
            Session cSession = webSocketSet.get(phone).session;
            if (cSession != null && cSession.isOpen()) {
                    sendMessage(message, cSession);
                return true;
            }}
        } catch (IOException e) {
            logger.error("向用户[%s]发送拨号通知失败，出现异常：[%s]",phone,e);
            throw new RuntimeException(e);
        }
        return  false;
    }

    /**
     * websocket 接收客户端消息
     *
     * @message message
     */
    @OnMessage
    public void onMessage(String message) {
        try {
            logger.info("appWebsocket：收到客户端消息:{}", message);
        } catch (Exception e) {
            logger.error("appWebsocket：接收客户端消息异常", e.getMessage());
        }
    }

}
